<template>
  <view class="box">
    <!-- 真实内容（用来测量高度） -->
    <view ref="realRef" class="real">
      <text>{{ text }}</text>
    </view>
    <text>初始化场景:</text>
    <!-- 实际展示（带裁剪） -->
    <view
      class="content"
      :style="{
        maxHeight: expanded ? 'none' : '200rpx',
      }"
    >
      <text>{{ text }}</text>
    </view>

    <!-- 展开/收起按钮（按需显示） -->
    <view v-if="overflow" class="btn" @tap="toggle">
      {{ expanded ? "收起" : "展开" }}
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from "vue";

const props = defineProps<{ text: string }>();

const expanded = ref(false);
const overflow = ref(false); // 是否超出
const realRef = ref();

/* 测量文字是否超出 200rpx */
async function checkOverflow() {
  await nextTick();
  const query = uni.createSelectorQuery().in(this); // this 指向当前组件实例
  query
    .select(".real")
    .boundingClientRect((rect) => {
      if (rect) overflow.value = rect.height > uni.upx2px(200);
    })
    .exec();
}

watch(() => props.text, checkOverflow, { immediate: true });

function toggle() {
  expanded.value = !expanded.value;
}
</script>

<style scoped lang="scss">
.box {
  padding: 20rpx;
  background-color: #111827;
  color: $uni-text-color-inverse;
}

/* 用于测量的真实容器，不占位 */
.real {
  position: absolute;
  left: -9999px;
  top: 0;
  width: 100%;
  word-break: break-all;
}

/* 实际展示容器 */
.content {
  overflow: hidden;
  line-height: 1.6;
  word-break: break-all;
  transition: max-height 0.35s ease-in-out;
  color: $uni-text-color-grey;
  font-size: 0.9rem;
}

.btn {
  color: #007aff;
  font-size: 28rpx;
  display: flex;
  justify-content: flex-end;
}
</style>